/**
 * SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
 * SPDX-License-Identifier: Mulan PSL v2
 */
<template>
    <div class="sql-form">
        <div class="sql-form__left-tree">
            <lang class="left-tree__title">数据集目录</lang>
            <!--            <sf-light-tree :data="dataSetsList"-->
            <!--                           default-width="90%"-->
            <!--                           tree-fold-icon=""-->
            <!--                           tree-expanded-fold-icon=""-->
            <!--                           default-height="calc(100% - 112px)"-->
            <!--                           tree-name="name"-->
            <!--                           tree-i-d="name"/>-->
            <div style="display: flex; align-items: center">
                <sf-textfield v-model="searchValue"
                              class="textfield-item"
                              trigger-type="comp-search"
                              :placeholder="_('输入搜索')"/>
                <i style="margin-top: 10px;margin-left: 16px;cursor: pointer"
                   class="sf-comp-iconfont icon-comp-refresh"
                   @click="getList"></i>
            </div>
            <el-tree ref="tree" :data="dataSetsList" :props="defaultProps" :filter-node-method="filterNode"></el-tree>
        </div>
        <div class="sql-form__edit">
            <div class="form-edit__title">
                <lang class="title__left">输入SQL执行脚本</lang>
                <span class="title__right" @click="showDrawer">
                    <i class="el-icon-question title-icon"/>
                    <span>
                        {{ _('SQL内置函数目录') }}
                    </span>
                </span>
            </div>
            <sql-editor ref="sqleditor"
                        style="height:calc(100% - 237px)"
                        :tables="sqlTables"
                        :readOnly="isDebugSuccess"
                        class="form-edit__body"
                        :placeholder="placeholder"
                        :value="value" @change-textarea="changeTextarea($event)"/>
            <div :class="['form-edit__footer', 'footer-flex--between' ,]">
                <span>
                    <sf-button-primary v-if="!isDebugSuccess" :loading="deBugLoad" @click="deBug">调试</sf-button-primary>
                    <sf-button-primary v-else @click="isDebugSuccess = false">再次编辑</sf-button-primary>
                    <span v-if="deBugLoad" class="sim-link" style="margin-left: 38px;" @click="stopDebug">取消</span>
                    <lang v-if="tableColumnNames.length>=30" style="color: red;margin-left: 30px;">
                        警告：当前输出字段较多，可能会导致任务执行时间过长，建议减少输出字段数量以降低等待时长。
                    </lang>
                </span>
                <div v-if=" tableColumnNames.length !== 0" class="edit-footer__table">
                    <sf-table ref="table" :options="tableOptions" :default-height="120">
                        <sf-table-column v-for="item in tableColumnNames" :key="item" :data-index="item"
                                         :default-width="120">{{ item }}
                        </sf-table-column>
                    </sf-table>
                </div>
            </div>
        </div>
        <sf-drawer :visible.sync="isShowDrawer"
                   :append-to-body="false"
                   :size="1265"
                   direction="rtl">
            <div slot="title">SQL内置函数目录</div>
            <div style="height: 100%; width: 100%;">
                <iframe src="static/sql/index.htm" style="height: 100%; width: 100%;border:none"></iframe>
            </div>
        </sf-drawer>
    </div>
</template>

<script>
import {isUndefined} from "src/util/typeof";

const DATASETS = '/task-manage/api/v1/datasets/catalog'
const DEBUG = '/task-manage/api/v1/sql/debug'
import sqlFormatter from './sqlFormatter'
import SqlEditor from './sql_editor'

export default {
    name: "SqlForm",
    components: {
        SqlEditor
    },
    data() {
        return {
            searchValue: '',
            value: this.$store.state.task.form.sqlText,
            dataSetsList: [],
            defaultProps: {
                children: 'children',
                label: 'name'
            },
            sqlTables: {},
            isShowDrawer: false,
            isDebugSuccess: false,
            deBugLoad: false,
            tableOptions: {
                selectionHide: true,
            },
            tableColumnNames: [],
            ajax: null,
        }
    },
    watch: {
        searchValue(val) {
            this.$refs.tree.filter(val);
        }
    },
    computed: {
        sqlText() {
            return sqlFormatter.format(this.value, {language: 'sql'})
        },
        placeholder() {
            return '/* 输入建议1：datalake_pulsar 及 datalake_latest 空间下的数据集建议指定分区字段dt（日期）进行查询以提升性能，如 where dt = "2022-11-01" */\n' +
                '/* 输入建议2：仅抽取所需字段可有效降低性能开销，降低等待时间，不建议使用 “select *” */'
        }
    },
    async mounted() {
        await this.getList()
    },
    methods: {
        async getList() {
            let {success, data} = await this.$ajax.get(DATASETS);
            if (!success) {
                return;
            }
            this.$closeNotifys();
            this.$ok(_('数据加载成功'), {autoHide: true})
            this.dataSetsList = data.list;
            this.sqlTables = data.tables
        },
        changeTextarea(val) {
            this.$set(this, 'value', val)
        },
        
        showDrawer() {
            this.isShowDrawer = true;
        },
        
        async deBug() {
            this.$closeNotifys();
            const vm = this
            this.tableColumnNames = [];
            if (this.sqlText === this.placeholder) {
                this.$warn(_('未输入SQL语句，请输入后再调试'), {autoHide: true})
                return;
            }
            this.deBugLoad = true;
            let jsonData = await this.$ajax.post(DEBUG, {
                    sqlText: this.sqlText,
                }, {
                    before(request) {
                        vm.ajax = request;
                    }
                }
            )
            this.deBugLoad = false;
            if (isUndefined(jsonData)) {
                return;
            }
            
            const {msg, data, success} = jsonData || {}
            if (!success) {
                this.$warn(msg || _('sql语句输入有误'), {autoHide: true})
                return;
            }
            this.isDebugSuccess = true;
            this.tableColumnNames = data.columnNames;
            this.$nextTick().then(() => {
                const tableData = this.tableColumnNames.reduce((obj, item, index) => {
                    obj[item] = data.columnTypes[index]
                    return obj
                }, {})
                this.$refs.table?.loadData([tableData]);
            })
        },
        
        isValid() {
            this.$closeNotifys();
            if (this.deBugLoad) {
                this.$warn('正在调试中，请先取消', {autoHide: true})
                return false;
            }
            if (this.sqlText === '') {
                this.$warn(_('未输入SQL语句，请输入'), {autoHide: true})
                return false;
            }
            if (!this.isDebugSuccess) {
                this.$warn(_('请先进行SQL调试，调试通过后方可进行下一步'), {autoHide: true})
                return false;
            }
            return true;
        },
        
        getJsonValue() {
            return {
                sqlText: this.sqlText,
            }
        },
        stopDebug() {
            if (this.ajax) {
                this.ajax.abort();
            }
        },
        filterNode(value, data) {
            if (!value) return true;
            return data.name.indexOf(value) !== -1;
        }
    }
}
</script>

<style scoped lang="less">
.sql-form {
    height: 100%;
    display: flex;
    padding: 0 66px;
    
    .sql-form__left-tree {
        width: 300px;
        
        .left-tree__title {
            padding-bottom: 16px;
            width: 90%;
            display: block;
            font-size: 14px;
            font-weight: 500;
            color: #3D3D3D;
            border-bottom: 1px solid #D8D8D8;
        }
        
        .textfield-item {
            margin-top: 10px;
            width: 80%;
        }
        
        //.sfv-tree {
        //    margin-top: 13px;
        //    overflow: auto;
        //
        //    /deep/ .sfv-table_body {
        //        .sfv-tree_row {
        //            .sfv-tree-cell {
        //                text-align: start !important;
        //            }
        //        }
        //    }
        //
        //}
        .el-tree {
            margin-top: 16px;
            overflow: auto;
            height: calc(100% - 157px);
            
            /deep/ .el-tree-node__content {
                height: 32px;
            }
        }
    }
    
    .sql-form__edit {
        flex: 1;
        
        .form-edit__title {
            display: flex;
            justify-content: space-between;
            margin-bottom: 16px;
            
            .title__left {
                font-size: 14px;
                font-weight: 500;
                color: #3D3D3D;
                position: relative;
                padding-left: 15px;
            }
            
            .title__left::before {
                content: "*";
                color: #e55;
                position: absolute;
                left: 2px;
                top: 3px;
            }
            
            .title__right {
                display: flex;
                align-items: flex-start;
                color: #165DFF;
                cursor: pointer;
                
                .title-icon {
                    font-size: 16px;
                    margin-right: 16px;
                }
                
                span:hover {
                    text-decoration: underline;
                }
            }
        }
        
        .form-edit__body {
            border: 1px solid #CCCFD9;
        }
        
        .form-edit__footer {
            display: flex;
            flex-wrap: wrap;
            padding-top: 16px;
            
            .edit-footer__table {
                width: 100%;
                max-width: 1132px;
                height: 120px;
                margin-top: 16PX;
            }
        }
        
        .footer-flex--end {
            justify-content: flex-end;
        }
        
        .footer-flex--between {
            justify-content: space-between;
        }
    }
    
    /deep/ .sf-dialog__wrapper {
        .sf-drawer {
            .sf-drawer__body {
                padding: 0;
                overflow: hidden;
            }
        }
    }
}
</style>
